﻿using System;
using System.Collections.Generic;
using System.Text;
using AutoMapper;
using FireBillBook.Core.Models.Options;
using FireBillBook.Core.Services;
using Microsoft.Extensions.DependencyInjection;

namespace FireBillBook.Core.Extensions
{
    public static class PlatformServiceBuilderExtension
    {

        /// <summary>
        /// 注入平台相关服务，指定名称和初始化方法
        /// </summary>
        /// <param name="services"></param>
        /// <param name="name"></param> 
        /// <param name="initService"></param>
        /// <returns></returns>
        public static PlatformServiceBuilder AddPlatform(this PlatformServiceBuilder builder, string name, Func<IServiceProvider, BasePlatformService> initService, string description = "暂无描述")
        {
            builder.Services.Configure<PlatformServiceFactoryOptions>(name, options => options.initPlatform = initService);
            builder.AddServiceInfo(name, description);
            return builder;
        }

        /// <summary>
        /// 注入平台相关服务
        /// </summary>
        /// <typeparam name="TPlatformService"></typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static PlatformServiceBuilder AddPlatform<TPlatformService>(this PlatformServiceBuilder builder) where TPlatformService : BasePlatformService, new()
        {
            return builder.AddPlatform<TPlatformService>(typeof(TPlatformService).Name, typeof(TPlatformService).FullName);
        }

        /// <summary>
        /// 注入平台相关服务, 自定义名称
        /// </summary>
        /// <typeparam name="TPlatformService"></typeparam>
        /// <param name="services"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static PlatformServiceBuilder AddPlatform<TPlatformService>(this PlatformServiceBuilder builder, string name, string description) where TPlatformService : BasePlatformService, new()
        {
            if (string.IsNullOrEmpty(name))
            {
                name = typeof(TPlatformService).Name;
            }

            if (string.IsNullOrEmpty(description))
            {
                description = typeof(TPlatformService).FullName;
            }

            builder.AddPlatform(name, (provider) =>
            {
                var service = new TPlatformService();
                service.Mapper = provider.GetRequiredService<IMapper>();
                return service;
            }, description);
            return builder;
        }

        public static PlatformServiceBuilder AddPlatformInfos(this PlatformServiceBuilder builder)
        {
            PlatformServiceInfoOptions options = new PlatformServiceInfoOptions()
            {
                Infos = builder.PlatformServiceInfos.Value
            };

            builder.Services.Configure<PlatformServiceInfoOptions>(options => options.Infos = builder.PlatformServiceInfos.Value);

            return builder;
        }


    }
}
